package com.example.demo.modules.customDefine.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.util.R;
import com.example.demo.modules.customDefine.entity.Supplier;
import com.example.demo.modules.customDefine.service.SupplierService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/api/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;


    @GetMapping("/listAll")
    public R listAll() {
        return R.ok().put("result", supplierService.list(null));
    }

    @GetMapping("/one")
    public R one(@RequestParam(value = "id", required = true) String id) {
        if(null == id || "".equals(id)){
            return R.error().put("msg", "缺少参数id");
        }

        return R.ok().put("result", supplierService.getById(id));
    }

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", dataType = "String")
    })
    public R page(
            Integer pageSize, Integer pageNum) {
        if (null == pageSize || "".equals(pageSize)) {
            pageSize = 10;
        }
        if (null == pageNum || "".equals(pageNum)) {
            pageNum = 0;
        }
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        return R.ok().put("result", supplierService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @PostMapping("/add")
    public R add(@RequestBody Supplier supplier) {
        return R.ok().put("result", supplierService.save(supplier));
    }

    @PostMapping("/update")
    public R update(@RequestBody Supplier supplier, HashMap<String, Object> updateOptions) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        if (null != supplier.getId() && !("".equals(supplier.getId()))) {
            queryWrapper.eq("id", supplier.getId());
        } else {
            return R.error("id不能为空");
        }
        return R.ok().put("result", supplierService.update(supplier, queryWrapper));
    }

    @GetMapping("/delete")
    public R deleteOne(@RequestParam(value = "id", required = true) String id) {
        return R.ok().put("result", supplierService.removeById(id));
    }
}
